package com.itheima.servcie;

import com.itheima.utils.JedisUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisDataException;
import java.util.Random;

public class JedisService {
    private String id;
    public JedisService(String id){
        this.id=id;
    }

    public void service(){
//        Jedis jedis = new Jedis("localhost", 6379);
        Jedis jedis= JedisUtils.getJedis();
        String value = jedis.get("compid:" + id);
        //判定是否具有调用计数控制，利用异常进行控制处理
        if(value == null) {
            //没有控制，创建控制计数器
            jedis.setex("compid:" + id, 20, ""+(Long.MAX_VALUE-10));
        }else{
            //有控制，自增，并调用业务
            try{
                Long val = jedis.incr("compid:"+id);
                business(id,10+val-Long.MAX_VALUE);
            }catch (JedisDataException e){
                //调用次数溢出，弹出提示
                System.out.println("用户："+id+"使用次数已达到上限，请稍后再试，或升级VIP会员");
                return;
            }finally{
                jedis.close();
            }
        }
    }

    public void business(String id,long num){
        System.out.println("用户"+id+"发起业务调用，当前第"+num+"次");
    }

}

class MyThread extends Thread {
    JedisService sc;

    public MyThread(String id){
        sc=new JedisService("id");
    }
    public void run() {
        while (true) {
            sc.service();
            //模拟调用间隔，设定为1.x秒
            try {
                Random r = new Random();
                Thread.sleep(1000 + r.nextInt(200));
            } catch (InterruptedException e) {
                e.printStackTrace();
                ;
            }
        }

    }
}

class main{
    public static void main(String[] args) {
        MyThread t1 = new MyThread("初级用户");
        t1.start();
    }
}